package com.cuiweiyou.bluemesh.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.cuiweiyou.bluemesh.base.BluetoothApp;
import com.cuiweiyou.bluemesh.model.LightModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class NicknameSqlUtil extends SQLiteOpenHelper {
    private static String db_name = "db_bluetooth";
    private static String tb_name = "tb_bluetooth";

    private List<String> addressList;
    private Map<String, List<LightModel>> allDeviceMap;

    private static NicknameSqlUtil instance;

    public static NicknameSqlUtil getInstance() {
        if (null == instance) {
            synchronized (NicknameSqlUtil.class) {
                if (null == instance) {
                    instance = new NicknameSqlUtil(BluetoothApp.getContext(), db_name, null, 1);
                }
            }
        }
        return instance;
    }

    private NicknameSqlUtil(Context context, String name_db, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name_db, factory, version);

        addressList = new ArrayList<>();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL( //
                    "CREATE TABLE " + tb_name //
                            + " ( "  //
                            + "_id INTEGER PRIMARY KEY AUTOINCREMENT"  //
                            + ", meshgroup VARCHA" //
                            + ", address VARCHA" //
                            + ", nickname VARCHAR" //
                            + " );" //
                  );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion && 2 == newVersion) {
        }
    }

    /////////////////////////////////////////////////////////////////////////////

    /**
     * 插入
     */
    public long insert(LightModel light, String nickName) {
        if (null == allDeviceMap) {
            queryAll(); // 提取曾经设备放置重复插入
        }

        String address = light.getAddress();
        String group = light.getName();

        if (addressList.contains(address)) {
            updateByAddress(address, nickName);
            return 0;
        }

        addressList.add(address);

        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("meshgroup", group);
        cv.put("address", address);
        cv.put("nickname", nickName);
        long id = db.insert(tb_name, null, cv);
        db.close();

        return id;
    }

    public int updateByAddress(String address, String nickName) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues cv = new ContentValues();
        cv.put("nickname", nickName);
        int count = db.update(tb_name, cv, "address = ?", new String[]{address});

        db.close();

        return count;
    }

    public String getNickName(String address) {
        String nickname = null;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(tb_name, new String[]{"nickname"}, "address = ?", new String[]{address}, null, null, null);
        if (cursor.moveToNext()) {    // 从第一行开始遍历，还有行就返回true
            nickname = cursor.getString(cursor.getColumnIndex("nickname"));
        }

        cursor.close();
        db.close();

        return nickname;
    }

    public List<LightModel> getGroup(String groupName) {
        List<LightModel> list = new ArrayList<>();

        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(tb_name, new String[]{"address", "nickname"}, "meshgroup = ?", new String[]{groupName}, null, null, null);

        int index = 1;
        while (cursor.moveToNext()) {    // 从第一行开始遍历，还有行就返回true
            long _id = cursor.getLong(cursor.getColumnIndex("_id"));
            String address = cursor.getString(cursor.getColumnIndex("address"));
            String nickname = cursor.getString(cursor.getColumnIndex("nickname"));

            LightModel lightModel = new LightModel(); // 按照组名从数据库提取曾经的设备
            lightModel.setNickname(nickname);
            lightModel.setAddress(address);

            list.add(lightModel);
            index++;
        }

        cursor.close();
        db.close();

        return list;
    }

    public Map<String, List<LightModel>> queryAll() {
        if (null == allDeviceMap) {
            allDeviceMap = new HashMap<>();
        } else {
            return allDeviceMap;
        }

        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + tb_name + " ORDER BY _id ASC", null);

        int index = 1;
        while (cursor.moveToNext()) {    // 从第一行开始遍历，还有行就返回true
            long _id = cursor.getLong(cursor.getColumnIndex("_id"));
            String meshgroup = cursor.getString(cursor.getColumnIndex("meshgroup"));
            String address = cursor.getString(cursor.getColumnIndex("address"));
            String nickname = cursor.getString(cursor.getColumnIndex("nickname"));

            List<LightModel> lightLight = allDeviceMap.get(meshgroup);
            if (null == lightLight) {
                lightLight = new ArrayList<>();
                allDeviceMap.put(meshgroup, lightLight);
            }

            LightModel lightModel = new LightModel(); // 从数据库提取全部设备
            lightModel.setNickname(nickname);
            lightModel.setAddress(address);

            lightLight.add(lightModel);

            if (!addressList.contains(address)) {
                addressList.add(address);
            }

            index++;
        }

        cursor.close();
        db.close();

        return allDeviceMap;
    }
}

